//
//  LBPageControl.m
//  LBPageControl
//
//  Created by liubo on 2023/6/10.
//

#import "LBPageControl.h"
#import "LBPageItemView.h"

@interface LBPageControl()
@property(nonatomic, strong)NSMutableArray *itemArray;
@end

@implementation LBPageControl

- (void)setPageCount:(NSInteger)pageCount
{
    _pageCount = pageCount;
    [self creatPageItemWithPageCount];
}

- (void)pageContolAnimationIndex:(NSInteger)index
{
    if (index <0) {
        index = _pageCount-1;
    }else if(index == _pageCount){
        index = 0;
    }
    self.currentPage = index;
    for (int i = 0; i<self.itemArray.count; i++) {
        LBPageItemView *item = self.itemArray[i];
        if (item.pageIndex == index) {
            item.isCurrentPage = YES;
        }else{
            item.isCurrentPage = NO;
        }
        [item scroProgressWithState:index];
    }
}

-(void)setScroProgress:(float)scroProgress {
    _scroProgress = scroProgress;
    NSInteger index =  self.currentPage;
    if (index <0) {
        index = _pageCount-1;
    }else if(index == _pageCount){
        index = 0;
    }
    self.currentPage = index;
    for (int i = 0; i<self.itemArray.count; i++) {
        LBPageItemView *item = self.itemArray[i];
        item.isLeftScro = self.isLeftScro;
        item.scroProgress = scroProgress;
        if (item.pageIndex == index) {
            item.isCurrentPage = YES;
        } else {
            item.isCurrentPage = NO;
        }
        [item scroProgressWithState:index];
    }
}

- (void)creatPageItemWithPageCount
{
    [self clearView];
    CGFloat itemWidth = 7;
    CGFloat variableWidth = 5;
    CGFloat itemHeight = 3;
    CGFloat itemMargin = 3;
    CGFloat itemWidthMu = variableWidth*(1-0);
    for (int i =0; i<_pageCount; i++) {
        CGFloat leftPadding = 0;
        CGFloat wideth  = itemWidth+itemWidthMu;
        if (i!=0) {
            leftPadding =  itemWidth*i+itemMargin*i+itemWidthMu;
            wideth = itemWidth;
        }
        
        LBPageItemView *item = [[LBPageItemView alloc]initWithFrame:CGRectMake(leftPadding, 7, wideth, itemHeight)];
        item.selectedColor = self.selectedItemColor;
        item.normalColor = self.normalItemColor;
        if (i==0) {
            item.isCurrentPage = YES;
        } else {
            item.isCurrentPage = NO;
        }
        item.pageIndex = i;
        [self addSubview:item];
        [self.itemArray addObject:item];
    }
}

-(void)clearView {
    [self.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
}

#pragma mark - lazy load

- (NSMutableArray *)itemArray
{
    if (!_itemArray) {
        _itemArray = [NSMutableArray array];
    }
    return _itemArray;
}

@end
